package thread.safe;

/**
 * 观察多线程场景下的线程安全问题
 */
public class ThreadUnsafeDemo {
    private static class Counter{
        public int getCount() {
            return count;
        }
       volatile int count = 0;
//        synchronized
        void increase(){
            count++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000 ; i++) {
                counter.increase();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        t1.start();
//        t1.join();
        t2.start();
        t1.join();
        t2.join();
        // t1 -> t2 -> main
        // 主线程走到此处，说明t1和t2都已经执行结束，理想状态count = 10w
        System.out.println("两个搬砖人都已经执行结束");
        System.out.println(counter.count);
    }
}
